package com.shirodemo.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @Auther: shenjj
 * @Date: 2019/3/4 16:27
 * @Todo: 自定义加密算法realm，散列算法采用md5、sha，加盐方式
 * 如：明文密码+帐号（盐）+散列次数
 */
public class MyPasswordRealm extends AuthorizingRealm{

    @Override
    public String getName(){
        return "MyPasswordRealm";
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        if(!"zhangsan".equals(username)){
            return null;
        }
        //模拟数据库中加密之后密文：明文密码+帐号（盐）+散列次数(2)
        String password = "baacc2a8c7428f490042a1e17db48b9a";
        /**
         * 功能描述: info对象表示realm登录比对信息
         * 参数1：用户信息
         * 参数2：密码
         * 参数3：加盐
         * 参数4：当前realm名称
         */
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo
                (username,password, ByteSource.Util.bytes("zhangsan"),getName());
        return info;
    }
}
